package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author fan
 * @date 2025-05-26
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private IElderService elderService;
    @Autowired
    private IBedService bedService;
    @Autowired
    private ICheckInConfigService checkInConfigService;
    @Autowired
    private IContractService contractService;


    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto 入住申请信息Dto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //查询老人信息，是否已记录，状态是否为已入住
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<Elder>();
        elderQueryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo());
        Elder elderDB = elderService.getOne(elderQueryWrapper);
        if (ObjectUtils.isNotEmpty(elderDB) && elderDB.getStatus() == 1) {
            //老人已入住
            throw new BaseException("老人已入住");
        }

        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();

        //1,处理老人信息
        Elder elder = BeanUtil.toBean(checkInElderDto, Elder.class);
        //补充床位信息
        Long bedId = checkInConfigDto.getBedId();
        elder.setBedId(bedId);
        elder.setStatus(1);
        Bed bed = bedService.getById(bedId);
        bed.setBedStatus(1);
        bedService.updateById(bed);
        String bedNumber = bed.getBedNumber();
        elder.setBedNumber(bedNumber);

        //判断是新增老人还是更新老人
        if (ObjectUtils.isEmpty(elderDB)){
            elderService.save(elder);
        }else {
            elderService.updateById(elder);
        }

        //2,处理合同信息
        Contract contract = BeanUtil.toBean(checkInContractDto, Contract.class);
        contract.setElderId(elder.getId());
        String number = "HT" + CodeGenerator.generateContractNumber();
        contract.setContractNumber(number);
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        Integer status = checkInConfigDto.getStartDate().isBefore(LocalDateTime.now()) ? 0 : 1;//设置合同状态
        contract.setStatus(status);
        contractService.save(contract);

        //3,处理入住信息
        CheckIn checkIn = BeanUtil.toBean(checkInConfigDto, CheckIn.class);
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bedNumber);
        checkIn.setStatus(0);
        //添加老人家属信息
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);

        //4,处理入住配置信息
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);

    }

    /**
     * 查询入住详情
     *
     * @param id 入住id
     * @return CheckInDetailVo 入住详情
     */
    @Override
    public CheckInDetailVo selectCheckInDetailById(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //1,查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);
        LambdaQueryWrapper<CheckInConfig> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigService.getOne(lambdaQueryWrapper);
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkIn, CheckInConfigVo.class);
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);

        //2,查询老人信息
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        elderLambdaQueryWrapper.eq(Elder::getId, checkIn.getElderId());
        Elder elder = elderService.getOne(elderLambdaQueryWrapper);
        //获取老人年龄
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        checkInElderVo.setAge(DateUtil.ageOfNow(elder.getBirthday()));

        //查询老人与家属关系
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(remark, ElderFamilyVo.class);

        //3,查询合同信息
        LambdaQueryWrapper<Contract> contractLambdaQueryWrapper = new LambdaQueryWrapper<>();
        contractLambdaQueryWrapper.eq(Contract::getElderId, elder.getId());
        Contract contract = contractService.getOne(contractLambdaQueryWrapper);

        //4,封装数据
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
